package com.example;

import java.util.Deque;
import java.util.LinkedList;
import java.util.List;

/**
 * @Author loubobooo
 * @Description #107. 二叉树的层序遍历 II
 * @Date 2022/3/2
 */
public class BinaryTreeLevelOrderTraversalIi {

    class TreeNode {
        int val;
        TreeNode left;
        TreeNode right;

        TreeNode() {
        }

        TreeNode(int val) {
            this.val = val;
        }

        TreeNode(int val, TreeNode left, TreeNode right) {
            this.val = val;
            this.left = left;
            this.right = right;
        }
    }

    /**
     * 方法描述:给你二叉树的根节点 root ，返回其节点值 自底向上的层序遍历 。 （即按从叶子节点所在层到根节点所在的层，逐层从左向右遍历）
     * 示例 1：
     *
     * 输入：root = [3,9,20,null,null,15,7]
     * 输出：[[15,7],[9,20],[3]]
     * @param: [root]
     * @return: java.util.List<java.util.List < java.lang.Integer>>
     * @author: loubobooo
     * @date: 2022/3/2
     */
    public List<List<Integer>> levelOrderBottom(TreeNode root) {
        LinkedList<List<Integer>> lists = new LinkedList<>();
        if (root == null) {
            return lists;
        }
        Deque<TreeNode> deque = new LinkedList<>();
        deque.add(root);
        while (!deque.isEmpty()) {
            List<Integer> list = new LinkedList<>();
            int count = deque.size();
            while (count > 0) {
                TreeNode poll = deque.poll();
                list.add(poll.val);
                if (poll.left != null) {
                    deque.add(poll.left);
                }
                if (poll.right != null) {
                    deque.add(poll.right);
                }
                count--;
            }
            lists.addFirst(list);
        }
        return lists;
    }
}
